package com.iuie.ns.frame.utils.httpclients;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iuie.ns.frame.exception.ServiceException;
import com.iuie.ns.frame.utils.StringUtils;

/**
 * httpDelete请求
 * @author liujie
 * @date 2018年6月2日下午5:14:53
 */
class HttpDeleteRequest implements IHttpRequest {
	
	private static final Logger logger = LoggerFactory.getLogger(HttpDeleteRequest.class);

	@Override
	public HttpResult send(HttpParams params) {
		try {
			String url = params.url();
			
			if (StringUtils.isBlank(url)) {
				throw new ServiceException("ERR: httpDelete请求失败，URL为空！");
			}
			
			HttpDelete httpDelete = new HttpDelete(url);
			
			// 设置HTTP请求头
			Map<String, String> headers = params.headers();
			headers.put("Accept", "*/*");
			headers.put("Accept-Encoding", "gzip, deflate, sdch");
			headers.put("Accept-Language", "zh-CN,zh;q=0.8");
			
			Iterator<Entry<String, String>> it = headers.entrySet().iterator();
			while (it.hasNext()) {
				Entry<String, String> en = it.next();
				httpDelete.setHeader(en.getKey(), en.getValue());
			}
			
			// 设置超时时间
			RequestConfig config = RequestConfig.custom()
				.setConnectTimeout(params.connectTimeout())
				.setSocketTimeout(params.socketTimeout()).build();
			httpDelete.setConfig(config);
			
			// 发送httpDelete请求
			CloseableHttpClient client = HttpClients.createDefault();
			CloseableHttpResponse resp = null;
			try {
				resp = client.execute(httpDelete);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new ServiceException("httpDelete请求失败，UnsupportedEncodingException");
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				throw new ServiceException("httpDelete请求失败，ClientProtocolException");
			} catch (IOException e) {
				e.printStackTrace();
				throw new ServiceException("httpDelete请求失败，IOException");
			}
			
			// 获取并返回响应信息
			return new HttpResult(resp.getEntity(), client, resp);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("ERR:执行httpDelete请求异常<br>url={}, 参数={}", params.url(), params.params());
			throw new ServiceException("ERR:执行httpDelete请求异常<br>url=" + params.url());
		}
	}

}
